package tcp_proxy_router

import (
	"context"
	"fmt"
	"log"

	"github.com/youkelike/gateway/dao"
	"github.com/youkelike/gateway/tcp_proxy_middleware"
	"github.com/youkelike/gateway/tcp_server"
)

var tcpServerList = []*tcp_server.Server{}

// type tcpHandler struct {
// }

// func (t *tcpHandler) ServeTCP(ctx context.Context, src net.Conn) {
// 	src.Write([]byte("tcpHandler\n"))
// }

func TcpServerRun() {
	serviceList := dao.ServiceManagerHandler.GetTcpServiceList()
	for _, serviceItem := range serviceList {
		tempItem := serviceItem
		go func(serviceDetail *dao.ServiceDetail) {
			// 构造路由，仅用于收集中间件
			router := tcp_server.NewTcpSliceRouter()
			router.Group("/").Use(
				tcp_proxy_middleware.TCPFlowCountMiddleware(),
				tcp_proxy_middleware.TCPFlowLimitMiddleware(),
				tcp_proxy_middleware.TCPWhiteListMiddleware(),
				tcp_proxy_middleware.TCPBlackListMiddleware(),
				// 熔断
				// tcp_proxy_middleware.TcpCircuitBreakMiddleware(),

				tcp_proxy_middleware.TCPReverseProxyMiddleware(),
			)

			// 构造 server
			addr := fmt.Sprintf(":%d", serviceDetail.TCPRule.Port)
			baseCtx := context.WithValue(context.Background(), "service", serviceDetail)
			tcpServer := &tcp_server.Server{
				Addr:    addr,
				Handler: router,
				BaseCtx: baseCtx,
			}
			tcpServerList = append(tcpServerList, tcpServer)

			// 启动 server
			log.Printf(" [INFO] tcp_proxy_run %v\n", addr)
			if err := tcpServer.ListenAndServe(); err != nil && err != tcp_server.ErrServerClosed {
				log.Fatalf(" [INFO] tcp_proxy_run %v err:%v\n", addr, err)
			}
		}(tempItem)
	}
}

func TcpServerStop() {
	for _, tcpServer := range tcpServerList {
		tcpServer.Close()
		log.Printf(" [INFO] tcp_proxy_stop %v stopped\n", tcpServer.Addr)
	}
}
